import axios from 'axios'

export default {
    namespaced: true,
    state: {
        id: 0,
        article: {},
        prev: {},
        next: {},
        items: [],
        list: [],
    },

    // 计算属性
    getters: {
        tags(state) {
            let strTags = state.article.keywords || '';
            return strTags.split(",");
        }
    },

    // 异步获取数据
    actions: {
        // 文章信息
        getArticle: ({commit, state}) => {
            axios.get("/vue/articles/show", {
                params: {"id": state.id}
            }).then(response => {
                if (response.data.code === 0) {
                    commit('setArticle', response.data.data.article || {});
                    commit('setNext', response.data.data.next || {});
                    commit('setPrev', response.data.data.prev || {});
                }
            });
        },

        // 文章列表
        getArticleList: ({commit, state}) => {
            axios.get("/vue/articles/index", {
                params: {
                    type_id: state.article.type_id,
                    limit: 6,
                }
            }).then(response => {
                if (response.data.code === 0) {
                    commit("setItems", response.data.data)
                }
            })
        },

        // 获取首页文章信息
        getList: ({commit, state}) => {
            axios.get("/vue/articles/index", {
                params: {
                    orderBy: "created_at desc,sort asc,id asc",
                    limit: 10,
                }
            }).then(response => {
                if (response.data.code === 0) {
                    commit("setList", response.data.data)
                }
            });
        },
    },

    // 同步提交
    mutations: {
        // 设置ID
        setArticleId(state, id) {
            state.id = id
        },

        // 设置文章信息
        setArticle(state, article) {
            state.article = article || {}
        },

        // 下一条
        setNext(state, next) {
            state.next = next || {}
        },

        // 上一条
        setPrev(stat, prev) {
            state.prev = prev || {}
        },

        // 文章列表
        setItems(state, items) {
            state.items = items
        },

        // 首页
        setList(state, list) {
            state.list = list;
        }
    }
}

